package com.llsydn.demo.shopList;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.llsydn.hello.R;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * @author lilinshen
 * @title 商品列表展示dmeo
 * @description 请填写相关描述
 * @date 2018/9/28 10:06
 */
public class ShopListActivity extends AppCompatActivity {
    private ListView lv_main;
    private LinearLayout ll_main_loading;
    private List<ShopInfo> data;
    private ShopInfoAdapter adapter;
    private static final int WHAT_SUCCESS = 1;
    private static final int WHAT_ERROR = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_SUCCESS:
                    ll_main_loading.setVisibility(View.GONE);
                    //显示列表
                    lv_main.setAdapter(adapter);
                    break;
                case WHAT_ERROR:
                    ll_main_loading.setVisibility(View.GONE);
                    Toast.makeText(ShopListActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_list);

        lv_main = findViewById(R.id.lv_main);
        ll_main_loading = findViewById(R.id.ll_main_loading);
        adapter = new ShopInfoAdapter();

        //1.主线程，显示提示图
        ll_main_loading.setVisibility(View.VISIBLE);

        //2.分线程,请求服务器动态加载数据并显示
        new Thread() {
            @Override
            public void run() {
                //联网请求得到json字符串
                try {
                    String result = requestShopList();
                    Log.e("TAG", result);
                    data = new Gson().fromJson(result, new TypeToken<List<ShopInfo>>() {
                    }.getType());
                    Log.e("TAG", data.toString());
                    //3.主线程，更新界面
                    handler.sendEmptyMessage(WHAT_SUCCESS);
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(WHAT_ERROR);
                }
            }
        }.start();

    }

    /**
     * 发送请求获取商品列表的json数组
     *
     * @return
     */
    private String requestShopList() {
        String result = "";
        String path = "http://192.168.4.124:8080/android/getAllShops";
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();
            if (200 == connection.getResponseCode()) {
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                baos.close();
                is.close();
                result = baos.toString();
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    class ShopInfoAdapter extends BaseAdapter {
        private ImageLoader imageLoader;

        public ShopInfoAdapter() {
            this.imageLoader = new ImageLoader(ShopListActivity.this, R.drawable.loading, R.drawable.error);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                convertView = View.inflate(ShopListActivity.this, R.layout.item_shop, null);
            }
            ShopInfo shopInfo = data.get(position);
            ImageView imageView = convertView.findViewById(R.id.iv_item_icon);
            TextView textName = convertView.findViewById(R.id.tv_item_name);
            TextView textContent = convertView.findViewById(R.id.tv_item_content);
            textName.setText(shopInfo.getName());
            textContent.setText(shopInfo.getPrice() + "元");
            String imagePath = shopInfo.getImagePath();
            //根据图片路径动态请求加载图片并显示（当前是在主线程，所以这里要启动分线程，动态加载图片显示）
            imageLoader.loadImage(imagePath, imageView);
            return convertView;
        }
    }

}
